package com.dhecp.project.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.domain.ModuleNID;
import com.dhecp.project.common.domain.RecordCheck;
import com.dhecp.project.common.domain.UpdateDeleted;
import com.dhecp.project.common.domain.UpdateFlow;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.hr.domain.TrainingAppraiseLecturer;
import com.dhecp.project.purchase.domain.OfflinePurchaseOrder;
import com.dhecp.project.purchase.mapper.OfflinePurchaseOrderMapper;
import com.dhecp.project.storage.domain.AssemblyMaintain;
import com.dhecp.project.storage.domain.OfflinePurchaseStorage;
import com.dhecp.project.storage.domain.PurchasingError;
import com.dhecp.project.storage.domain.StockControl;
import com.dhecp.project.storage.mapper.*;
import com.dhecp.project.storage.service.OfflinePurchaseStorageService;
import com.dhecp.project.storage.service.PurchaseStorageService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: kjecp
 * @description: 采购入库 服务实现层
 * @author: hlf
 * @create: 2022-09-01 10:43
 */
@Service
public class OfflinePurchaseStorageServiceImpl extends BaseModuleServiceImpl implements OfflinePurchaseStorageService {


    @Autowired
    private OfflinePurchaseStorageMapper storageMapper;
    @Autowired
    private OfflinePurchaseOrderMapper orderMapper;
    @Autowired
    private AssemblyMaintainMapper maintainMapper;
    @Autowired
    private StockControlMapper stockControlMapper;
    @Autowired
    private PurchasingErrorMapper purchasingErrorMapper;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    /**
     * @Description: 查询前一单NID、BID
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: com.dhecp.common.core.domain.AjaxResult  (data.nid 前一单NID， data.bid 前一单BID)
     * @Author: hlf
     * @date: 2022-05-09 10:08
     */
    @Override
    public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        ModuleNID moduleNID = storageMapper.selectLastNid(params);
        if (moduleNID == null) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     * @Description: 查询后一单NID、BID
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: com.dhecp.common.core.domain.AjaxResult  (data.nid 后一单NID， data.bid 后一单BID)
     * @Author: hlf
     * @date: 2022-05-09 10:09
     */
    @Override
    public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        ModuleNID moduleNID = storageMapper.selectNextNid(params);
        if (moduleNID == null) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     * @Description: 查询指定单nid的首记录
     * @Param: [params]
     * @return: com.dhecp.project.storage.domain.OfflinePurchaseStorage
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public OfflinePurchaseStorage queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return storageMapper.selectFirstRecordByNid(params);
    }

    /**
     * @Description: 查询指定单nid的整单录
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: java.util.List<com.dhecp.project.storage.domain.OfflinePurchaseStorage>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<OfflinePurchaseStorage> queryListByNid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return storageMapper.selectByNid(params);
    }

    /**
     * @Description: 查询指定单nid的整单录
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: java.util.List<com.dhecp.project.storage.domain.OfflinePurchaseStorage>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public OfflinePurchaseStorage queryByGuid(String guid) {
        return storageMapper.findByGuid(guid);
    }


    /**
     * @Description: 查询
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.storage.domain.OfflinePurchaseStorage>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<OfflinePurchaseStorage> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return storageMapper.select(params);
    }

    /**
     * @Description: 查询
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.storage.domain.OfflinePurchaseStorage>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<OfflinePurchaseStorage> queryGroupList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return storageMapper.selectGroup(params);
    }

    /**
     * @Description: 查询采购订单数据
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.storage.domain.OfflinePurchaseStorage>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<OfflinePurchaseStorage> selectOrderData(Map<String, Object> params) throws Exception {
        return storageMapper.selectOrderData(params);
    }

    /**
     * @Description: 查询线下采购订单数据
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.storage.domain.OfflinePurchaseStorage>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<OfflinePurchaseStorage> selectOfflineOrderData(Map<String, Object> params) throws Exception {
        return storageMapper.selectOfflineOrderData(params);
    }

    /**
     * @Description: 查询线下采购入库数据
     */
    @Override
    public List<OfflinePurchaseStorage> selectOfflinePurchaseStorage(String bid) throws Exception {
        return storageMapper.selectOfflinePurchaseStorage(bid);
    }

    /**
     * @Description: 保存
     * @Param: [params] moduleTable 必要参数：功能唯一标识
     * @Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @SuppressWarnings("unchecked")
    @Override
    public AjaxResult saveData(Map<String, Object> params) {
        params.put("businessEntity", new OfflinePurchaseStorage());

        List<OfflinePurchaseStorage> list = JSON.parseArray(params.get("infoItems").toString(), OfflinePurchaseStorage.class);

        for (OfflinePurchaseStorage item : list
        ) {
            OfflinePurchaseOrder order = orderMapper.findByGuid(item.getpGuid());
            if (order != null && item.getInqty() > order.getNinqty()) {
                return AjaxResult.error("订单到货数量不可超过未到货数量");
            }
        }

        AjaxResult ajaxResult = this.saveDataBase(params);
        if (!"0".equals(ajaxResult.get("code").toString())) {
            throw new RuntimeException(ajaxResult.get("msg").toString());
        }

        String resNid = "0";
        Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        List<OfflinePurchaseStorage> businessDataList = (List<OfflinePurchaseStorage>) ajaxResult.get("businessDataList");


        List<RecordCheck> guidMapList = storageMapper.findRecords(infoMap.get("nid").toString());
        Map<String, Object> guidMap = new HashMap<String, Object>();
        if (!guidMapList.isEmpty()) {
            if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())) { //单号重复验证
                throw new RuntimeException(MessageUtils.message("module.error.retry"));
            }
            for (RecordCheck recordCheck : guidMapList) {
                if (recordCheck != null && recordCheck.getGuid() != null) {
                    guidMap.put(recordCheck.getGuid().toString(), "1");
                }
            }
        }

        if (businessDataList == null || businessDataList.size() == 0) {
            resNid = "0";
        } else {
            resNid = infoMap.get("nid").toString();
            int i = 0;
            for (OfflinePurchaseStorage businessData : businessDataList) {
                String guid = "";
                if (businessData.getGuid() == null) {
                    guid = RandomValueUtils.getGUID();
                } else {
                    guid = businessData.getGuid().toString();
                }
                businessData.setGuid(guid);
                OfflinePurchaseOrder order = orderMapper.findByGuid(businessData.getpGuid());
//                if (businessData.getsNum()>businessData.getInqty()){
//                    businessData.setNinqty(order.getNinqty()-businessData.getInqty());//未到货数量
//                }else{
//                    businessData.setNinqty(0);
//                    businessData.setInqty(businessData.getsNum());
//                }
                if (order != null) {
                    if (businessData.getInqty() >= order.getNinqty()) {
                        businessData.setNinqty(0);
                        businessData.setInqty(order.getNinqty());
                    } else {
                        businessData.setNinqty(order.getNinqty() - businessData.getInqty());//未到货
//                    businessData.setAmountPaid(businessData.getOrderAmount());
                    }
                }

                businessData.setIid(i);

                for (String field : infoMap.keySet()) { //遍历非网格字段，并赋值到实体中
                    Object fieldValue = infoMap.get(field);
                    ReflectUtils.setValue(businessData, field, fieldValue);
                }

                if (guidMap.get(guid) == null) {
                    businessData.setCreateTime(new Date());
                    storageMapper.insert(businessData);
                } else {
                    storageMapper.update(businessData);
                    guidMap.remove(guid);
                }
                i++;
            }
        }

        if (!guidMap.isEmpty()) {
            for (String guid : guidMap.keySet()) {
                storageMapper.delete(guid);
            }
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), resNid);
    }

    /**
     * @Description: 删除
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult deleteData(Map<String, Object> params) {
        List<OfflinePurchaseStorage> businessDataList = JSON.parseArray(params.get("infoItems").toString(), OfflinePurchaseStorage.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (OfflinePurchaseStorage businessData : businessDataList) {
            storageMapper.delete(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * @Description: 修改删除标志（预留）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串（仅需 guid 和 deleted）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateDeleted(Map<String, Object> params) {
        List<UpdateDeleted> updateDeletedList = JSON.parseArray(params.get("infoItems").toString(), UpdateDeleted.class);
        if (updateDeletedList == null || updateDeletedList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (UpdateDeleted updateDeleted : updateDeletedList) {
            storageMapper.updateDeleted(updateDeleted);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * @Description: 流转  —— 添加流程任务、修改流程状态及生效标志
     * @Param: [params] tableDataId 必要参数：单据编码（nid）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateFlowGo(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack", "单据编码【tableDataId】"));
        } else {
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<OfflinePurchaseStorage> businessDataList = storageMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        } else {
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == "") {
            params.put("optType", "go");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (OfflinePurchaseStorage businessData : businessDataList) {
            if (updateFlow.getActiveFlow().equals("end")) {//当流程结束时
                OfflinePurchaseOrder order = orderMapper.findByGuid(businessData.getpGuid());
                if (order != null) {
                    order.setAliPlace(businessData.getPlace());//物流渠道
                    order.setAliLogisticsCode(businessData.getTrackingNumber());//物流单号
                    order.setWarehouse(businessData.getBid());//入库单号

                    order.setNinqty(order.getNinqty() - businessData.getInqty());
                    order.setInqty(order.getInqty() + businessData.getInqty());
                    if (businessData.getNinqty() == 0) {
                        order.setState("已入库");
                    }
                    orderMapper.update(order);
                }

                //进行入库操作
                //生成新库存 --
//                AddStockControl(businessData);

            }
            updateFlow.setGuid(businessData.getGuid().toString());
            storageMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     * @Description: 退回  —— 添加流程任务、修改流程状态及生效标志
     * @Param: [params] tableDataId 必要参数：单据编码（nid）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateFlowBack(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack", "单据编码【tableDataId】"));
        } else {
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<OfflinePurchaseStorage> businessDataList = storageMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        } else {
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == "") {
            params.put("optType", "back");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (OfflinePurchaseStorage businessData : businessDataList) {
            if (businessDataList.get(0).getEffectStock() && !updateFlow.getEffectStock()) { //当流程重置时
                OfflinePurchaseOrder order = orderMapper.findByGuid(businessData.getpGuid());
                if (order != null) {

                    order.setAliPlace("");//物流渠道
                    order.setAliLogisticsCode("");//物流单号
                    order.setWarehouse("");//入库单号

                    order.setState("未入库");

                    order.setNinqty(order.getNinqty() + businessData.getInqty());
                    order.setInqty(order.getInqty() - businessData.getInqty());
                    orderMapper.update(order);
                    //删除入库信息
//                    DelStockControl(businessData);
                }
            }
            updateFlow.setGuid(businessData.getGuid().toString());
            storageMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }


    /**
     * @Description: 修改审核状态
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-12-08 9:15
     */
    @Override
    @Transactional(timeout = 120, propagation = Propagation.REQUIRES_NEW)
    public AjaxResult updateType(Map<String, Object> params) {
        List<OfflinePurchaseStorage> purchaseStorages = JSON.parseArray(params.get("infoItems").toString(), OfflinePurchaseStorage.class);
        OfflinePurchaseStorage purchaseStorage;
        Date date = new Date();
        for (OfflinePurchaseStorage item : purchaseStorages
        ) {
            purchaseStorage = storageMapper.findByGuid(item.getGuid());

            Map<String, Object> paramsStorage = new HashMap<String, Object>();
            paramsStorage.put("nid", purchaseStorage.getNid());
            List<OfflinePurchaseStorage> list = storageMapper.selectByNid(paramsStorage);

            for (OfflinePurchaseStorage item2 : list
            ) {
                if (!purchaseStorage.getEffectStock()){
                    return AjaxResult.error("当前流程未结束!");
                }
                item2.setState(item.getState());

                if (item.getState().equals("已入库")) {
                    item2.setWarehouseTime(date);
                    storageMapper.update(item2);

                    //修改入库时间
                    OfflinePurchaseOrder order = orderMapper.findByGuid(item2.getpGuid());
                    if (order != null) {
                        order.setWarehouseTime(date);
                        orderMapper.update(order);
                    }
                    //生成新库存 --
                    AddStockControl(item2);
                } else {
                    item2.setWarehouseTime(null);
                    storageMapper.updateWarehouseTime(item2);

                    orderMapper.updateWarehouseTime(item2.getpGuid());

                    DelStockControl(item2);
                }
            }


        }
        return AjaxResult.success("操作成功!");
    }


    /**
     * @Description: 导入
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-12-08 9:15
     */
    @Override
    public AjaxResult saveImportData(Map<String, Object> params) {

        List<OfflinePurchaseStorage> purchaseStorageList = JSON.parseArray(params.get("infoItems").toString(), OfflinePurchaseStorage.class);
        if (purchaseStorageList == null || purchaseStorageList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        int x = 0;
        for (OfflinePurchaseStorage item : purchaseStorageList) {

            Map<String, Object> params2 = new HashMap<String, Object>();
            params2.put("trackingNumber", item.getTrackingNumber());
            List<OfflinePurchaseStorage> purchaseStorages = storageMapper.findByBID(params2);

            if (purchaseStorages.size() > 0) {
                for (OfflinePurchaseStorage item2 : purchaseStorages
                ) {
                    item.setAuditor(ShiroUtils.getUserId());
                    item2.setUpdateTime(new Date());
                    item2.setState("已入库");
                    item.setvZzZt("未组装");
                    storageMapper.update(item2);
                }
            }
            x++;
        }
        return AjaxResult.success(x + "条数据导入成功");
    }

    public void AddStockControl(OfflinePurchaseStorage item) {

        Double cost = 0.00;


        if (item.getPlanID().contains("CGBC")) {//判断数据是否来着采购报错
            PurchasingError order = purchasingErrorMapper.findByGuid(item.getpGuid());
            cost = order.getSonPrice();
        } else {
            OfflinePurchaseOrder order = orderMapper.findByGuid(item.getpGuid());
            cost = order.getPrice();
        }

        StockControl newStock = new StockControl();//生成新的库存数据
        //判断是否存在库存数据
        Map<String, Object> params2 = new HashMap<String, Object>();
        params2.put("rkGuid", item.getGuid());
        params2.put("vGsBm", item.getvGsBm());
        params2.put("vHw", item.getGoodsAllocation());
        params2.put("vKq", item.getGoodsArea());
        params2.put("gDepot", item.getWarehouseAddress());
        params2.put("productcode", item.getsCode());
        newStock = stockControlMapper.findByMultiparameter(params2);

        if (newStock == null){
            StockControl stockControl = new StockControl();
            stockControl.setGuid(RandomValueUtils.getGUID());
            stockControl.setProductNum(item.getInqty());//可用数量
            stockControl.setProductNumAll(item.getInqty());//库存总数
            stockControl.setRkGuid(item.getGuid());//入库标识
            stockControl.setRkBid(item.getBid());//入库单号
            stockControl.setIsParent("0");//是否母件
            stockControl.setvHw(item.getGoodsAllocation());//入库货位
            stockControl.setvKq(item.getGoodsArea());//库区
            stockControl.setgDepot(item.getWarehouseAddress());//所在仓库
            stockControl.setvGsBm(item.getvGsBm());//公司编码
            stockControl.setvGsJc(item.getvGsJc());//公司简称
            stockControl.setvGsMc(item.getvGsMc());//公司名称
            stockControl.setProductCode(item.getsCode());//商品编码
            stockControl.setProductName(item.getsName());
            ;//商品名称
//        stockControl.setPurchasePrice(order.getPrice());//商品采购价
            stockControl.setPurchasePrice(cost);//商品采购价
            stockControl.setPurchaseTotalPriceAll(cost * item.getInqty());//采购总价
            stockControl.setAllotPrice(0.00);//调拨单价
            stockControl.setTotalAllotPrice(0.00);//调拨总价
            stockControl.setsDays(0);//库存天数
            stockControl.setPurchaseStorageID(item.getBid());//采购入库单
            stockControl.setPurchaseOrderID(item.getPlanID());//采购订单
            stockControl.setPurchasePlanID(item.getOrderID());//采购计划单
            stockControl.setdRkSj(new Date());//入库日期
            stockControl.setCreateTime(new Date());//创建日期
            stockControlMapper.insert(stockControl);
        }

    }


    private void DelStockControl(OfflinePurchaseStorage businessData) {
        StockControl newStock = new StockControl();//生成新的库存数据
        //判断是否存在库存数据
        Map<String, Object> params2 = new HashMap<String, Object>();
        params2.put("rkGuid", businessData.getGuid());
        params2.put("vGsBm", businessData.getvGsBm());
        params2.put("vHw", businessData.getGoodsAllocation());
        params2.put("vKq", businessData.getGoodsArea());
        params2.put("gDepot", businessData.getWarehouseAddress());
        params2.put("productcode", businessData.getsCode());
        newStock = stockControlMapper.findByMultiparameter(params2);
        if (newStock != null) {//还原库存
            //删除库存信息
            stockControlMapper.deleteStockControl(newStock.getGuid());
        }
    }
}